<script setup lang="ts">
import { ref, reactive , toRefs } from 'vue';
import { add, update } from '@/api/system/role';
import { notify } from '@/utils/element';
import type {SysRoleType} from "@/types/system";

//定义自定义事件
const emit = defineEmits(['refresh']);

const formRef = ref();

const initData = {status: '0'};

const state = reactive({
    loading: false,
    visible: false,
    title: '新增',
    type: 'add' as FormType,
    formData: {} as SysRoleType,
});

const { loading, visible, title, formData } = { ...toRefs(state)};

defineExpose({
    open,
});

function open(type: FormType, title: string, data= {} as any) {
    state.type = type;
    state.title = title;
    //合并初始数据，深度拷贝，不然会影响原数据
    state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
    state.visible = true;
}

function close() {
    if(state.loading) return;
    formRef.value?.resetFields();
    state.visible = false;
}

//提交表单
function submitForm() {
    formRef.value?.validate((valid: boolean) => {
        if(!valid) return;
        //调用接口，提交数据
        submitData();
    });
}

async function submitData() {
    try {
        state.loading = true;
        let res: any = {};
        if(state.type === 'edit') {
            res = await update(state.formData);
        }else {
            res = await add(state.formData);
        }
        state.loading = false;
        if(res.code !== 200) return;
        notify('操作成功！', {type: 'success'});
        //关闭窗口
        close();
        //触发父组件重新加载数据
        emit('refresh');
    } catch (error) {
    } finally {
        state.loading = false;
    }
}
</script>

<template>
    <el-dialog :title="`${title}角色`" v-model="visible"
    center draggable :before-close="close" width="500px"
    :close-on-click-modal="false" destroy-on-close>
        <el-form v-loading="loading" ref="formRef" :model="formData" label-width="85px" label-position="right" status-icon label-suffix=":">
            <el-form-item label="角色名称" prop="roleName" :rules="{required: true,message:'角色名称为必填项！',trigger:'blur'}">
                <el-input v-model="formData.roleName" placeholder="请输入角色名称" maxlength="30" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="角色编码" prop="roleKey" :rules="{pattern: /^[a-zA-Z0-9_]{2,30}$/,message:'只允许输入2~30位英文/数字/下划线！',trigger:'blur'}">
                <el-input v-model="formData.roleKey" placeholder="请输入角色编码" maxlength="30" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="角色状态" prop="status" :rules="{required: true,message:'角色状态为必填项！',trigger:'change'}">
                <el-switch v-model="formData.status"
                    inline-prompt
                    active-text="启"
                   active-value="0"
                   inactive-value="1"
                    inactive-text="停"
                />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" maxlength="100" show-word-limit></el-input>
            </el-form-item>
        </el-form>
        <el-row justify="center" class="mt10">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
        </el-row>
    </el-dialog>
</template>

<style scoped>

</style>
